package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @WebFilter
 *      属性:
 *            String[] urlPatterns():拦截的路径
 *            String filterName():给过滤器设置名称:默认当前类名 (不需要书写)
 *
 *            String[] value() :设置拦击路径:如果是指定一个属性并且 value属性,value省略不写
 *           DispatcherType[] dispatcherTypes ():配置拦截的链路规则
 *                  DispatcherType.REQUEST:直接请求拦截 (默认值)
 *                  DispatcherType.FOWARD:请求转发拦截
 *                  DispatcherType.INCLUDE:包含指定的路径的时候拦截
 *              WebInitParam[] initParams():配置过滤器的初始化参数
 *
 *
 */

/**
 * 解决全局中文的乱码的过滤器
 * 配置的url-pattern:拦截所有
 */
@WebFilter("/*")
public class CharacterFilter implements Filter { //自定义类实现Fileter


    public void init(FilterConfig config) throws ServletException {
        System.out.println("全局过滤器初始化了");
    }

    //过滤任务
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws ServletException, IOException {

        //将req,resp---转成HttpServletRequest  HttpServletResonse:web容器创建
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //浏览器发送请求资源文件的时候,需要将请求对象的信息携带服务器,
        //通过拦截器.获取请求方式
        String method = request.getMethod();
//        System.out.println(method);
        if(method.equalsIgnoreCase("post")){
            //解决post中文乱码
            request.setCharacterEncoding("utf-8");
        }

        //解决响应的中文乱码
        response.setContentType("text/html;charset=utf-8");

        //放行
        chain.doFilter(req, resp); //放行:父接口
    }

    public void destroy() {
        System.out.println("全局过滤器销毁了...");
    }


}
